import React, { useState } from 'react';
import { Layout } from 'tdesign-react';
import AppHeader from './components/Header';
import HomePage from './pages/HomePage';
import CreatePostPage from './pages/CreatePostPage';
import AboutPage from './pages/AboutPage';
import 'tdesign-react/es/style/index.css';

const { Content } = Layout;

const App = () => {
  const [currentPage, setCurrentPage] = useState('home');
  const [posts, setPosts] = useState([
    {
      id: 1,
      title: 'React 学习笔记',
      content:
        'React 是一个用于构建用户界面的 JavaScript 库。它采用组件化的思想，让开发变得更加高效和可维护。',
      author: 'dolmo',
      date: '2025-09-30',
      tags: ['React', '前端', '学习'],
    },
    {
      id: 2,
      title: '我的第一篇博客',
      content: '这是我的第一篇博客文章内容。在这里我可以分享我的想法和经验。',
      author: 'dolmo',
      date: '2025-09-30',
      tags: ['介绍', '博客'],
    },
  ]);
  const [editingPost, setEditingPost] = useState(null);

  const handleNavChange = (key) => {
    setCurrentPage(key);
    if (key !== 'create') {
      setEditingPost(null);
    }
  };

  const handleSubmitPost = (post) => {
    if (editingPost) {
      // 更新文章
      setPosts(posts.map((p) => (p.id === post.id ? post : p)));
    } else {
      // 新增文章
      setPosts([post, ...posts]);
    }
    setCurrentPage('home');
    setEditingPost(null);
  };

  const handleEditPost = (post) => {
    setEditingPost(post);
    setCurrentPage('create');
  };

  const handleDeletePost = (id) => {
    setPosts(posts.filter((post) => post.id !== id));
  };

  const handleCancel = () => {
    setCurrentPage('home');
    setEditingPost(null);
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <AppHeader activeKey={currentPage} onNavChange={handleNavChange} />
      <Content>
        {currentPage === 'home' && (
          <HomePage
            posts={posts}
            onEdit={handleEditPost}
            onDelete={handleDeletePost}
          />
        )}
        {currentPage === 'create' && (
          <CreatePostPage
            post={editingPost || undefined}
            onSubmit={handleSubmitPost}
            onCancel={handleCancel}
          />
        )}
        {currentPage === 'about' && <AboutPage />}
      </Content>
    </Layout>
  );
};

export default App;
